import cors from 'cors';
import express from 'express';
import morgan from 'morgan';
import * as path from 'path';

import { format } from '@donnu-prod-practice/utils';

import { db, models } from './db';
import { environment } from './environments/environment';
import { ErrorHandlingMiddleware } from './middleware/ErrorHandlingMiddleware';
import { pathToRoot } from './other/constants';
import router from './routes/router';

const start = async (app: express.Express, port: number) => {
  console.log('------------ Welcome to donnu-prod-practice.antogor.ru server ------------');

  /* --------------------------------- setting -------------------------------- */

  app.use(cors({ origin: 'http://localhost:4200', credentials: true }));

  app.use(
    morgan((tokens, req, res) => {
      const date = format.date(new Date());
      const url = `${req.method}\t${req.originalUrl}`;
      const status = res.statusCode;
      const log = `[${date}] ${url} > ${status}`;
      return log;
    })
  );

  app.use(express.json());

  /* -------------------------------- / setting ------------------------------- */

  /* --------------------------------- routes --------------------------------- */

  app.use('/api', router);

  /* -------------------------------- / routes -------------------------------- */

  /* --------------------------------- client --------------------------------- */

  const pathToStaticSite = path.resolve(pathToRoot, '..', 'client');

  app.use(express.static(pathToStaticSite));
  app.get('*', (req: express.Request, res: express.Response) => {
    return res.sendFile('index.html', { root: pathToStaticSite });
  });

  /* -------------------------------- / client -------------------------------- */

  /* ----------------------------- error handling ----------------------------- */

  app.use(ErrorHandlingMiddleware);

  /* ---------------------------- / error handling ---------------------------- */

  try {
    /* ---------------------------- connecting to db ---------------------------- */

    console.time('Connecting to Database');
    await db.authenticate();
    await db.sync({ alter: true });
    console.timeEnd('Connecting to Database');

    /* --------------------------- / connecting to db --------------------------- */

    /* ------------------------- starting express server ------------------------ */

    console.time('Starting the server');
    const server = app.listen(port, () => {
      console.log(`Server started on port ${port}`);
      console.timeEnd('Starting the server');
    });

    /* ------------------------ / starting express server ----------------------- */

    /* --------------------------- sync db models data -------------------------- */

    models.Country.sync();

    /* -------------------------- / sync db models data ------------------------- */

    server.on('error', console.error);
  } catch (error) {
    console.error(error, "server don't started");
  }
};

start(express(), environment.PORT);
